package com.training.config;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.training.entity.Permission;
import com.training.entity.Role;
import com.training.entity.RolePermission;
import com.training.entity.RoleUser;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: environment-supervision
 * @BelongsPackage: com.training.config
 * @Author: Tianyu Han
 * @CreateTime: 2024-05-27  09:39
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String s) {
        List<String> permissions = new ArrayList<>();
        Db.lambdaQuery(RoleUser.class).eq(RoleUser::getUserId, loginId).oneOpt().ifPresent(roleUser -> {
            //RolePermission和Permission联表查询
            List<RolePermission> rolePermissions = Db.lambdaQuery(RolePermission.class).eq(RolePermission::getRoleId, roleUser.getRoleId()).list();
            rolePermissions.forEach(rolePermission -> {
                //获取权限id
                String permissionId = rolePermission.getPermissionId();
                //获取权限名称
                Permission permission = Db.lambdaQuery(Permission.class).eq(Permission::getId, permissionId).one();
                String permissionName = permission.getName();
                //将权限名称加入权限列表
                permissions.add(permissionName);
            });
        });
        return permissions;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String s) {
        List<String> list = new ArrayList<>();
        Db.lambdaQuery(RoleUser.class).eq(RoleUser::getUserId, loginId).oneOpt().ifPresent(roleUser -> {
            Db.lambdaQuery(Role.class).eq(Role::getId, roleUser.getRoleId()).oneOpt().ifPresent(role -> {
                list.add(role.getRoleName());
            });
        });
        return list;
    }
}
